<template>
  <div class="edit">
    <ElRow>
      <ElCol :xl="6" :lg="6" :md="24" :sm="24" :xs="24">
        <div class="editleft">
          <div>
            <li>
              <div v-if="route.params.typeby=='add'||route.params.typeby=='' "@click="saveedit('保存草稿')">保存草稿</div>
              <div v-if="route.params.typeby=='add'||route.params.typeby==''" @click="saveedit('提交发布')">提交发布</div>
               <div v-if="route.params.typeby=='uopdate'" @click="saveedit('提交修改')">提交修改</div>
            </li>
            <li> <el-popover :width="300">
                <template #reference>
                  <p class="popoverp">
                  <p>
                    <Icons type="icon-leidatance" style="font-size: 18px;"></Icons>权限选择
                  </p>
                  <p><el-text class="mx-1" :type="typelist[postxx.pr]">{{ postxx.prName }}</el-text>></p>
                  </p>
                </template>
                <template #default>
                  <el-tag style="margin-left: 5px;cursor: pointer;margin-top: 2px;"
                    v-for="(item, index) in permissiontypelist" @click="xuanzeprorlable(item, 'pr')"
                    :type="typelist[index]">{{ item.permisname }}</el-tag>
                </template>
              </el-popover>
            </li>
            <li v-if="postxx.pr == '4' || postxx.pr == '5'">

              <p class="popoverp">
                <el-input-number style="width: 90%;" v-model="postxx.number" :min="0" :max="10000">
                  <!-- <template #prefix>
                    <span>￥</span>
                  </template> -->
                </el-input-number>
              </p>


            </li>
            <li> <el-popover :width="300">
                <template #reference>
                  <p class="popoverp">
                  <p>
                    <Icons type="icon-leidatance" style="font-size: 18px;"></Icons>板块
                  </p>
                  <p><el-text class="mx-1" :type="typelist[postxx.lable]">{{ postxx.lableName }}</el-text>></p>
                  </p>
                </template>
                <template #default>
                  <el-tag style="margin-left: 5px;cursor: pointer;margin-top: 2px;"
                    v-for="(item, index) in fromlablelist" @click="xuanzeprorlable(item, 'lable')"
                    :type="typelist[index]">{{ item.labelname }}</el-tag>
                </template>
              </el-popover>
            </li>

          </div>
        </div>
      </ElCol>
      <ElCol :xl="18" :lg="18" :md="24" :sm="24" :xs="24">
        <div class="textbt">
          <div class="textbt_edtor">
            <textarea maxlength="15" type="text" class="line-form-input input-lg new-title textareas" name="post_title"
              tabindex="1" v-model="postxx.postitle" placeholder="请输入标题" rows="1" autoheight="false"
              maxheight="78"></textarea>
            <Toolbar class="Toolbar" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
            <Editor class="Editor" v-model="valueHtml" :defaultConfig="editorConfig" :mode="mode"
              @onCreated="handleCreated" />
          </div>
        </div>
      </ElCol>
    </ElRow>
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, reactive, shallowRef, computed, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElRow, ElCol, ElMessage, ElTag, ElText, ElInputNumber, ElPopover } from 'element-plus'
import { Icons } from 'ikicons'
import { addpost } from '@/api/request/post/index'
import { isOverSize } from '@/function/utlis'
import { useCounterStore } from '@/store/index.js'
import { useRoute } from 'vue-router'
const route=useRoute()
const typelist = ['primary', 'success', 'info', 'warning', 'danger']
const store = useCounterStore()
const uid = computed(() => store.userid)
const permissiontypelist = computed(() => store.publidata.permissiontypelist)
const fromlablelist = computed(() => store.publidata.fromlablelist)
const editorRef = shallowRef()
const postxx = reactive({
  pr: '', // 权限
  prName: '', // 权限名称
  lable: '', // 板块
  lableName: '', // 板块名称
  number: 0,
  postid:'',
  html: '',
  postitle: '',
  text: '',
})
const previewMode = ref(false) // 是否预览模式
// 内容 HTML
const valueHtml = ref('<p>请输入</p>')
// 模拟 ajax 异步获取内容

const toolbarConfig = { excludeKeys: ["group-video", "insertTable", "codeBlock"], } // 隐藏视频上传按钮
const editorConfig = {
  placeholder: "请输入内容...",
  autoFocus: !previewMode.value,
  scroll: true,
  maxLength: 10000,
  readOnly: previewMode.value,
  MENU_CONF: {
    uploadImage: {
      customUpload(file, insertFn) {
        const MAX_SIZE = 0.5 * 1024 * 1024; // 5MB
        if (file.size > MAX_SIZE) {
          // toast.error('图片大小不能超过5MB');
          ElMessage.error('图片大小不能超过500KB');
          return;
        }

        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const base64 = reader.result;
          insertFn(base64, file.name);
        };
      },
    },
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  console.log(editorRef.value.getAllMenuKeys())
}
// permissiontypeid labelid
const xuanzeprorlable = ((id, type) => {
  postxx[type] = id.permissiontypeid || id.labelid
  postxx[type + 'Name'] = id.permisname || id.labelname
  console.log(postxx)
})
const changepostXx = () => {
  console.log(editorRef.value.getText());

  if (!postxx.postitle) {
    ElMessage.error('请输入标题')
    return
  }
  if (!postxx.pr) {
    ElMessage.error('请选择权限')
    return
  }
  if (!postxx.lable) {
    ElMessage.error('请选择板块')
    return
  }
  if (postxx.pr == '4' || postxx.pr == '5') {
    if (postxx.number <= 0) {
      ElMessage.error('请输入正确的价格')
      return
    }
  }


  if (editorRef.value.getText() == '请输入' || editorRef.value.getText() == '') {
    ElMessage.error('请输入文档内容')
    return
  }
  postxx.text = editorRef.value.getText().slice(0, 30)
  postxx.html = editorRef.value.getHtml()
}
const saveedit = async (type) => {
  changepostXx()
  switch (type) {
    case '保存草稿':
       if(isOverSize(JSON.stringify(docs))) return ElMessage.error('草稿内容过大，请精简内容');
        localStorage.setItem("保存草稿", JSON.stringify(docs));
      break;
    case '提交发布':
      const res = await addpost({uid:uid.value,...postxx})
      if (res.status == 200) {
      ElMessage.success('提交发布成功等待审核通过');
      }else{
      ElMessage.error('提交发布失败');
      }
      break;

    default:
      break;
  }
}
const getpostXxbyid=async()=>{
  
}
</script>

<style>
@import '@/assets/css/Edit.css';
</style>